<template>
  <div class="login-container">
    <el-form
      ref="loginform"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="login-form"
    >
      <h2 class="login-title">会员管理系统</h2>
      <el-form-item label="账户" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('loginform')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import LoginUtils from "@/api/login";
export default {
  data() {
    return {
      form: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        console.log("valid", valid);
        if (valid) {
          LoginUtils.login(this.form.username, this.form.password).then(
            response => {
              console.log("response data", response.data);
              const respData = response.data;
              if (respData.flag) {
                LoginUtils.getUserInfo(respData.data.token).then(
                  userInfoResponse => {
                    const respUserInfoData = userInfoResponse.data;
                    if (respUserInfoData.flag) {
                      localStorage.setItem(
                        "mms-user",
                        JSON.stringify(respUserInfoData.data)
                      );
                      localStorage.setItem("mms-token", respData.data.token);

                      this.$message({
                        message: `登录成功!`,
                        type: "success",
                        duration: 500
                      });
                      this.$router.push("/");
                    }
                  }
                );
              } else {
                this.$message({
                  message: `登录失败! msg:${respData.message}`,
                  type: "warning",
                  duration: 500
                });
              }
            }
          );
        } else {
          this.$message({
            message: `校验失败!`,
            type: "warning"
          });
          return false;
        }
      });
    }
  }
};
</script>
<style>
.login-form {
  width: 30%;
  margin: 160px auto;
  padding: 28px;
  background-color: aliceblue;
  border-radius: 20px;
}
.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  box-shadow: 0 0 25px #8a1616;
  background-color: cornflowerblue;
  /* background: url("../../assets/beijing.png") */
}
.login-title {
  /* color: azure; */
  text-align: center;
}
</style>
